import 'package:boss/ui/widget/radioList/radio_item.dart';
import 'package:flutter/material.dart';
import 'model/radio_item_data.dart';

typedef RadioListBuilder<T> = Widget Function(BuildContext context, T value, bool isSelected);

class RadioList<T> extends StatelessWidget {
  final List<RadioItemData<T>> items;
  final List<T> value;
  final EdgeInsets padding;
  final ValueChanged<List<T>> onChanged;
  final bool isMultiple;
  final RadioListBuilder<T> builder;

  const RadioList({
    Key key,
    @required this.items,
    @required this.value,
    this.padding,
    this.onChanged,
    this.isMultiple = false,
    this.builder,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      padding: padding ?? EdgeInsets.zero,
      itemBuilder: (context, index) {
        var current = items[index];
        var isSelected = value.contains(current.value);

        if (builder != null) {
          var widget = builder(context, current.value, isSelected);
          widget = GestureDetector(
            onTap: () {
              handle(current, isSelected);
            },
            child: widget,
          );
          return widget;
        }

        return RadioItem(
          title: current.title,
          isSelected: isSelected,
          onTap: () {
            handle(current, isSelected);
          },
        );
      },
      itemCount: items.length,
    );
  }

  handle(RadioItemData<T> current, bool isSelected) {
    if (onChanged != null) {
      if (isMultiple) {
        var copy = List<T>.from(value);

        if (isSelected) {
          copy.remove(current.value);

          onChanged(copy);
        } else {
          List<T> temp = [];
          items.forEach((item) {
            if (value.contains(item.value) || item.value == current.value) {
              temp.add(item.value);
            }
          });

          onChanged(temp);
        }
      } else {
        onChanged([current.value]);
      }
    }
  }
}
